import dbunit.DBunitUtil
import dbunit.test.DBunitTests
import grails.util.GrailsUtil
import javax.sql.DataSource
import org.apache.log4j.Logger
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.dbunit.dataset.xml.XmlDataSet
import setupx.entity.Experiment
import exquery.common.TaxDivisionUtil
import exquery.common.SpeciesUtil
import exquery.common.OrganUtil
import exquery.common.LogUtil
import setupx.entity.ExperimentClass
import setupx.entity.ClassSample
import exquery.common.ProjectInitMap

class BootStrap {

     Logger gLogger = Logger.getLogger(BootStrap.class)
     DataSource dataSource

     def init = { servletContext ->

       if (GrailsUtil.getEnvironment() == GrailsApplication.ENV_TEST) {
          gLogger.info("initializing test dataset...")

          DBunitUtil.initialize(dataSource, new XmlDataSet(new FileReader(DBunitTests.DEFAULT_DATASET)))

          gLogger.info("database size: ${Experiment.count()}")
          gLogger.info("you should now be good to go")
       }else{
           // Load Primary data

           TaxDivisionUtil.getInstance().setUniqueDivisions()
           SpeciesUtil.getInstance().setUniqueSxSpecies()
           OrganUtil.getInstance().setUniqueSxOrgans()
           LogUtil.getInstance().setLastUpdateDate()
       }
       long experimentSize = Experiment.count()
       long classesSize = ExperimentClass.count()
       long samplesSize = ClassSample.findAllByLabelIsNotNullAndLabelNotEqual("")?.size()

       ProjectInitMap.getInstance().put("EXPERIMENT_COUNT",experimentSize)
       ProjectInitMap.getInstance().put("CLASSES_COUNT",classesSize)
       ProjectInitMap.getInstance().put("SAMPLES_COUNT",samplesSize)
     }

     def destroy = {
     }
} 